package org.acme.rest.client.weather;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.smallrye.mutiny.Uni;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.jboss.resteasy.annotations.jaxrs.PathParam;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import java.util.function.Function;

/**
 * @description: WeatherResource
 * @author: general
 * @version: 1.0
 * @create: 2022-03-07 00:13
 **/
@Path("/weather")
public class WeatherResource {

    @Inject
    @RestClient
    WeatherService weatherService;

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 同步方式
     * @param city
     * @return
     */
    @GET
    @Path("/city/{city}")
    public ResponseEntity city(@PathParam String city) throws JsonProcessingException {
        String cityWeather = weatherService.getByCity(city);
        return objectMapper.readValue(cityWeather, ResponseEntity.class);
    }

    /**
     * 响应式编程方式
     * @param city
     * @return
     */
    @GET
    @Path("/city/async/{city}")
    public Uni<ResponseEntity> cityAsync(@PathParam String city) {
        return Uni.createFrom().completionStage(weatherService.getByCityAsync(city)).onItem()
                .transform((Function<String, ResponseEntity>) weatherCity -> {
                    ResponseEntity responseEntity = new ResponseEntity();
                    try {
                        responseEntity = objectMapper.readValue(weatherCity, ResponseEntity.class);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                    return responseEntity;
                });
    }


}
